package tsing.javase.threadLocal;

/**
 * @Date 2024/8/6 14:07
 * @Author Tsing
 */
public class ThreadLocalDemo {

    public static void main(String[] args) {
        innitThreadLocalMethod2();

    }


    /**
     * 初始化ThreadLocal的方法
     *  正常在父线程中创建一个ThreadLocal，子线程是拿不到里面的值的，
     *  如果需要拿到子线程中的值，可以重写ThreadLocal.withInitial()方法
     */
    private static void innitThreadLocalMethod() {
        ThreadLocal<Integer> threalLocal = ThreadLocal.withInitial(() -> 6);
        Integer[] j =  {0};
        for ( int i = 0; i < 5; i++) {
            j[0] = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.printf( "第"+j[0]+"原：" +threalLocal.get());
                    threalLocal.set(threalLocal.get()+1);
                    System.out.println("第"+j[0]+"现：" +threalLocal.get());
                }
            }).start();

        }
    }


    /**
     * 初始化ThreadLocal方法2:通过InheritableThreadLocal保证ThreadLal在子线程的可见性
     *
     */
    private static void innitThreadLocalMethod2() {

        ThreadLocal<String> threadLocal = new ThreadLocal<>();
        InheritableThreadLocal<String> inheritableThreadLocal =
                new InheritableThreadLocal<>();

        Thread thread1 = new Thread(() -> {
            System.out.println("===== Thread 1 =====");
            threadLocal.set("Thread 1 - ThreadLocal");
            inheritableThreadLocal.set("Thread 1 - InheritableThreadLocal");

            System.out.println(threadLocal.get());
            System.out.println(inheritableThreadLocal.get());

            Thread childThread = new Thread( () -> {
                System.out.println("===== ChildThread =====");
                System.out.println(threadLocal.get());
                System.out.println(inheritableThreadLocal.get());
            });
            childThread.start();
        });

        thread1.start();

        Thread thread2 = new Thread(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("===== Thread2 =====");
            System.out.println(threadLocal.get());
            System.out.println(inheritableThreadLocal.get());
        });
        thread2.start();

    }
}
